from django.conf import settings
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from fdfs_client.client import Fdfs_client, get_tracker_conf

from goods.models import SKUImage, SKU
from meiduo_admin.serializers.images import ImagesSerializer, SkusSerializer
from meiduo_admin.utils import PageNum


class ImagesView(ModelViewSet):
    permission_classes = [IsAdminUser]
    queryset = SKUImage.objects.all()
    serializer_class = ImagesSerializer
    pagination_class = PageNum

    def simple(self, request):
        """
        获取sku商品的信息
        :param request:
        :return:
        """
        # 获取所有的sku商品信息
        skus = SKU.objects.all()
        # 序列化返回sku商品信息
        ser = SkusSerializer(skus, many=True)
        # 返回序列化结果
        return Response(ser.data)

    # def create(self, request, *args, **kwargs):
    #     """重写保存方法,保存图片地址"""
    #     # 1.获取前端数据
    #     data = request.data
    #     # 2.验证数据
    #     ser = self.get_serializer(data=data)
    #     ser.is_valid()
    #     # 3.建立fdstdfs的客户端
    #     tracker_config = get_tracker_conf(settings.FASTDFS_PATH)
    #     client = Fdfs_client(trackers=tracker_config)
    #     file = request.FILES.get('image')
    #     # 4.上传图片
    #     res = client.upload_by_buffer(file.read())
    #     # 5.判断图片是否上传成功
    #     if res['Status'] != 'Upload successed.':  # Status是str类型
    #         return Response({'error': '图片上传失败'})
    #     # 6.保存图片表
    #     # Remote file_id是字节类型
    #     img = SKUImage.objects.create(sku_id=request.data.get('sku')[0], image=res['Remote file_id'].decode())
    #     # 7.返回保存后图片的信息
    #     return Response({
    #         'id': img.id,
    #         'sku': img.sku_id,
    #         'image': img.image.url
    #     })
